package com.frame.project.service.system.post.imp;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.frame.common.constant.UserConstants;
import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.text.Convert;
import com.frame.framework.web.error.WebError;
import com.frame.framework.web.service.imp.AbstractBaseService;
import com.frame.project.domain.system.post.Post;
import com.frame.project.domain.system.user.UserPost;
import com.frame.project.repository.system.post.PostRepository;
import com.frame.project.repository.system.user.UserPostRepository;
import com.frame.project.service.system.post.PostService;

/**
 * 
 * @className ：PostServiceImpl
 * @describe ：岗位
 */
@Service
public class PostServiceImpl extends AbstractBaseService<Post> implements PostService {

	@Autowired
	private PostRepository postRepository;
	
	@Autowired
	private UserPostRepository userPostRepository;
	
	/**
	 * 分页
	 */
	@Override
	public Page<Post> findByPage(Integer pageNo, Integer pageSize, Post post) {
		List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.ASC, "orderNum"));
		Sort sort = Sort.by(orders);
		Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
		
		Page<Post> page = postRepository.findAll((root, query, cb) ->{
			List<Predicate> list = new ArrayList<>();
			list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));
			
			if(StringUtils.isNotBlank(post.getPostCode())) {
				list.add(cb.and(cb.like(root.get("postCode").as(String.class), post.getPostCode())));
			}
			
			if(StringUtils.isNotBlank(post.getStatus())) {
				list.add(cb.and(cb.equal(root.get("status").as(String.class), post.getStatus())));
			}
			
			if(StringUtils.isNotBlank(post.getPostName())) {
				list.add(cb.and(cb.like(root.get("postName").as(String.class), post.getPostName())));
			}
			
			Predicate[] p = new Predicate[list.size()];
			return cb.and(list.toArray(p));
		},pageable);
		
		return page;
	}
	
	/**
     * 查询所有岗位
     * 
     * @return 岗位列表
     */
    @Override
    public List<Post> selectPostAll()
    {
        return findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
    }
    
    /**
     * 根据用户ID查询岗位
     * 
     * @param userId 用户ID
     * @return 岗位列表
     */
    @Override
    public List<Post> selectPostsByUserId(Long userId)
    {
    	List<UserPost> upList = userPostRepository.findByUser_Id(userId);
    	List<Post> userPosts = new ArrayList<Post>();
    	for(UserPost up : upList) {
    		Post p = findById(up.getPost().getId());
    		userPosts.add(p);
    	}
        List<Post> posts = findAllByRs(RemoveEnum.NOT_REMOVE.getCode());
        for (Post post : posts)
        {
            for (Post userRole : userPosts)
            {
                if (post.getId() == userRole.getId())
                {
                    post.setFlag(true);
                    break;
                }
            }
        }
        return posts;
    }
    
    /**
     * 批量删除岗位信息
     * (物理删除）
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public WebError deletePostByIds(String ids)
    {
        Long[] postIds = Convert.toLongArray(ids);
        for (Long postId : postIds)
        {
            Post post = findById(postId);
            if (countUserPostById(postId) > 0)
            {
                return new WebError(-1, post.getPostName() + "已分配,不能删除");
            }
        }
        
        for(Long pId : postIds) {
        	delete(pId);
        }
        
        return new WebError();
    }
    
    /**
     * 通过岗位ID查询岗位使用数量
     * 
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public Integer countUserPostById(Long postId)
    {
        return userPostRepository.countUserPostById(postId);
    }
    
    /**
     * 校验岗位名称是否唯一
     * 
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(Post post)
    {
        Long postId = StringUtils.isNull(post.getId()) ? -1L : post.getId();
        Post info = postRepository.findByPostName(post.getPostName());

        if (StringUtils.isNotNull(info) && info.getId() != postId)
        {
            return UserConstants.POST_CODE_NOT_UNIQUE;
        }
        return UserConstants.POST_CODE_UNIQUE;
    }
    
    /**
     * 校验岗位编码是否唯一
     * 
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(Post post)
    {
        Long postId = StringUtils.isNull(post.getId()) ? -1L : post.getId();
        Post info = postRepository.findByPostCode(post.getPostCode());
        if(info == null) {
        	return UserConstants.POST_NAME_UNIQUE;
        }
        if (StringUtils.isNotNull(info) && info.getId() != postId)
        {
            return UserConstants.POST_CODE_NOT_UNIQUE;
        }
        return UserConstants.POST_CODE_UNIQUE;
    }
    
    @Override
    public void updatePost(Post post) {
    	Post p = findById(post.getId());
    	p.setPostName(post.getPostName());
    	p.setPostCode(post.getPostCode());
    	p.setOrderNum(post.getOrderNum());
    	p.setStatus(post.getStatus());
    	p.setRemark(post.getRemark());
    	
    	modify(p);
    }
}
